package com.github.baichuan.gb32960.codec;

import com.github.baichuan.gb32960.utils.ByteBufHelper;
import com.github.baichuan.iot.protocol.pdu.Decoder;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 极值数据
 */
public class ExtremeValue implements Decoder {
    @Override
    public List<Map<String, Object>> decode(ByteBuf buf) {
        Map<String, Object> data = new TreeMap<>();

        // 最高电压电池子系统代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxVoltageSubSystem", value);
        });

        // 最高电压电池单体代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxVoltageCell", value);
        });

        // 电池单体电压最高值
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("maxVoltage", BigDecimal.valueOf(value * 0.001).setScale(3, RoundingMode.HALF_UP));
        });

        // 最低电压电池子系统代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("minVoltageSubSystem", value);
        });

        // 最低电压电池单体代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("minVoltageCell", value);
        });

        // 电池单体电压最低值
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("minVoltage", BigDecimal.valueOf(value * 0.001).setScale(3, RoundingMode.HALF_UP));
        });

        // 最高温度子系统代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxTempSubSystem", value);
        });

        // 最高温度探针序号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("maxTempProbe", value);
        });

        // 最高温度值
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("maxTemp", value - 40);
        });

        // 最低温度子系统代号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("minTempSubSystem", value);
        });

        // 最低温度探针序号
        ByteBufHelper.readUnsignedByte(buf).ifPresent(value -> {
            data.put("minTempProbe", value);
        });

        // 最低温度值
        ByteBufHelper.readUnsignedShort(buf).ifPresent(value -> {
            data.put("minTemp", value - 40);
        });

        return Arrays.asList(data);
    }
}
